<?php
/**
 * 游戏表
 */
namespace Plu\Library\Models\Platform\Game;

use Phalcon\Mvc\Model,
    Phalcon\DI,
    Phalcon\Db\Column;

class Category extends Model {
    public $Id;

    public $Name;

    public $Domain;

    public $Skin;

    public $ParentId;

    public $Short;

    public $Path;

    public $IsLast;

    public $LogoUrl;

    public $IconUrl;

    public $MobileLogoUrl;

    public $HomeLogoUrl;

    public $SortBy;

    public $_index;

    public $CreateUser;

    public $CreateTime;

    public $UpdateUser;

    public $UpdateTime;

    public $DeleteUser;

    public $DeleteTime;

    public $DeleteFlag;

    const SKIN_TGA = 4;

    const SKIN_PLU = 2;

    const SKIN_ALL = self::SKIN_TGA | self::SKIN_PLU;

    public function initialize() {
        $this->setReadConnectionService('db.platform.slave');
    }

    public function getSource() {
        return "Category";
    }

    static public function getItem($id) {
        $item = self::findFirst(array(
            "Id = :id:",
            "bind" => array(
                'id' => $id
            ),
            "bindTypes" => array(
                'id' => Column::BIND_PARAM_INT
            )
        ));

        if ($item == false) {
            return [];
        } else {
            return $item->toArray();
        }
    }

    static public function getCategories($pid = 0, $skin = 0) {
        $guid = sprintf('categories_p%s_s%s', $pid, $skin);
        $cache_handler = DI::getDefault()->get('cache');
        $items = $cache_handler->get($guid);

        if (empty($items)) {

            $sql = "ParentId = :pid: AND DeleteFlag = 0";
            $bind = array(
                'pid' => $pid
            );
            $bindTypes = array(
                'pid' => Column::BIND_PARAM_INT
            );
            if ($skin & self::SKIN_ALL > 0) {
                $sql .= " Skin & :skin: = :skin:";

                $bind['skin'] = $skin;
                $bindTypes['skin'] = Column::BIND_PARAM_INT;
            }

            $params = array(
                $sql,
                'bind'      => $bind,
                'bindTypes' => $bindTypes
            );


            $data = self::find($params);
            $data = $data->toArray();

            $items = array();
            array_walk($data, function($item) use (&$items) {
                $items[] = array(
                    'id'       => $item['Id'],
                    'name'     => $item['Name'],
                    'domain'   => $item['Domain'],
                    'tag'      => $item['Domain'],
                    'isLast'   => $item['IsLast'],
                    'path'     => $item['Path'],
                    'logo'     => $item['LogoUrl'],
                    'parentId' => $item['ParentId']
                );
            });

            $cache_handler->save($guid, $items);
        }

        return $items;
    }

    /**
     * 0属于全部
     * 现在0的parentid为-1,这样可以避免全部游戏自动进入列表
     */
    public static function getCategoriesList($skin = 0, $pid = 0, $force = false) {
        $items = self::getCategories($pid, $skin);

        $categories = array();
        $categoriesByGroup = array();

        for ($c = 0, $len = count($items); $c < $len; $c++) {
            $item = $items[$c];

            $categories[] = $item;

            if ($item['isLast'] == 0) {
                list($_categories, $_categoriesByGroup) = self::getCategoriesList($skin, $item['id'], $force);

                //children
                $item['children'] = $_categoriesByGroup;
                $categories = array_merge($categories, $_categories);
            }

            $categoriesByGroup[] = $item;
        }

        $data = array($categories, $categoriesByGroup);

        return $data;
    }

    /**
     * 获取所有数据信息
     */
    static public function getGames($skin = 0) {
        $guid = sprintf('categories_%s', $skin);

        $cache_handler = DI::getDefault()->get('cache');

        $items = $cache_handler->get($guid);

        if (empty($items)) {
            $sql = "DeleteFlag = 0 AND Id != 0";
            $bind = array();
            $bindTypes = array();

            if ($skin & self::SKIN_ALL > 0) {
                $sql .= " Skin & :skin: = :skin:";

                $bind['skin'] = $skin;
                $bindTypes['skin'] = Column::BIND_PARAM_INT;
            }

            $params = array(
                $sql,
                'bind'      => $bind,
                'bindTypes' => $bindTypes
            );

            $data = self::find($params);

            $data = $data->toArray();
            $items = array();
            $_subgames = array();

            //这里需要把相关的父类全部收集，无限级分类

            array_walk($data, function($item) use (&$items, &$_subgames) {
                $parentid = $item['ParentId'];

                $items[$item['Id']] = array(
                    'id'         => $item['Id'],
                    'name'       => $item['Name'],
                    'domain'     => $item['Domain'],
                    'tag'        => $item['Domain'],
                    'short'      => $item['Short'],
                    'isLast'     => $item['IsLast'],
                    'path'       => $item['Path'],
                    'logo'       => $item['LogoUrl'],
                    'mobilelogo' => $item['MobileLogoUrl'],
                    'icon'       => $item['IconUrl'],
                    'skin'       => $item['Skin'],
                    '_index'     => $item['_index'],
                    'parentId'   => $item['ParentId']
                );

                if ($parentid > 0) {
                    //搜集子类id
                    if (empty($_subgames[$parentid])) {
                        $_subgames[$parentid] = array();
                    }
                    $_subgames[$parentid][] = $item['Id'];
                }
            });

            //数据合并
            if (!empty($_subgames)) {
                foreach ($_subgames as $gameid => $data) {
                    if (!empty($items[$gameid])) {
                        $item = $items[$gameid];
                        $parentId = $item['parentId'];

                        if ($parentId > 0) {
                            //合并到上层的parnet
                            if (empty($items[$parentId]['subgames'])) {
                                $_items = $_subgames[$parentId];
                            } else {
                                $_items = $items[$parentId]['subgames'];
                            }

                            $items[$parentId]['subgames'] = array_values(array_unique(array_merge($_items, $data)));
                        }

                        if (empty($items[$gameid]['subgames'])) {
                            $items[$gameid]['subgames'] = $data;
                        }
                        $items[$gameid]['subgames'][] = $gameid;
                    }
                }
            }

            $cache_handler->save($guid, $items);
        }

        return $items;
    }
}
